Adding some more judges, here and there.
[and.git] / UVa / 11590 - Prefix lookup / asmaa.cpp
blob4a452c00ce0b3ab8c5fdddf0b2890251a98ef970
1 struct trie_node {
3 // how many nodes are beneath this one?
4 int count;
6 // array of pointers to children
7 trie_node *child_list[ALPH_SIZE];
9 // initializer...
10 trie_node();
13 trie_node::trie_node() {
15 // there is nothing below us...
16 count = 0;
18 // all child pointers start out pointing nowhere...
19 for(int index = 0; index < ALPHABET_SIZE; index++)
20 child_list[index] = NULL;
25 class Trie {
27 public:
29 // methods
31 Trie(int level, int chars); // create it
32 ~Trie(); // destroy trie nodes
33 int node_count; // the number of nodes in whole trie
34 void AddToTrie(const string \&s); // add string to trie
36 private:
38 // methods
40 void recursive_delete (trie_node * t); // recursive delete helper function
44 // data
46 int node_count; // number of nodes in the trie
47 trie_node * Root; // the root of the trie
53 Trie::Trie() {
54 node_count = 0;
55 Root(new trie_node);
59 Trie::~Trie() {
61 // delete whole trie
62 recursive_delete(myRoot);
66 void Trie::recursive_delete(trie_node * t) {
67 int index;
69 if (t != NULL) {
71 // delete all children
72 for(index = 0; index < ALPHABET_SIZE; index++)
73 recursive_delete(t->child_list[index]);
75 // delete self
76 delete t;
83 int Trie::node_count() {
85 return (node_count);
91 void Trie::AddToTrie(const string \&s) {
92 int lcv, index;
94 trie_node *t = Root;
96 // there is one more string stored somewhere under the root...
97 t->count++;
100 // loop over the length of the string to add and traverse the trie...
101 for(lcv=0; lcv < s.length(); lcv++) {
103 index = s[lcv]; // the character in s we are processing...
105 // is there a child node for this character?
106 if (t->child_list[index] == NULL) {
108 // if not, make one!
109 t->child_list[index] = new trie_node;
110 node_count++;
113 // there is another string under this node...
114 t->child_list[index]->count++;
116 // move to it this node... and loop
117 t = t->child_list[index];
121 int N, M;
124 int main(){
125 while (cin >> N >> M && (N || M)){
126 Trie t;
127 unsigned long long i;
128 string str;
129 for(i=0; i<N; i++)
131 cin>>str;
132 str = str.substr(0, str.size() - 1); //to remove the *
133 t.AddToTrie(str);
135 cin>>N;
136 for(i=0; i<N; i++)
138 trie_node *r = t.Root; //I must keep the root of the Trie because I will change it later.
139 cin>>str;
140 str = str.substr(0, str.size() - 1);
141 unsigned long long j = 0;
142 for(j=0; j<str.size(); j++)
144 t.Root = t.Root->child_list[str[j] - '0'];
146 unsigned long long res = t.Find(str, 1);
147 cout<<res<<endl;
148 t.Root = r; //go back to the original root.
150 cout<<endl;
152 return 0;